package com.fulu.javabase.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

public class DeadLockTest {

    public static void main(String[] args) throws InterruptedException {
        // 线程1线获取到锁1，线程2线获取到锁2，
        // 然后线程1等待锁2被释放，线程2等待锁1被释放，造成死锁
        Thread t1 = new Thread(new MyThread(1));
        Thread t2 = new Thread(new MyThread(2));
        t1.start();
        t2.start();
        Thread.sleep(1000);
        // 将线程1强行中断，程序可继续执行
        // 加锁时，必须使用lockInterruptibly方法，否则不能终止。
        t1.interrupt();
    }

}

class MyThread implements Runnable{
    private int num;
    public static final ReentrantLock lock1 = new ReentrantLock();
    public static final ReentrantLock lock2 = new ReentrantLock();

    public MyThread(int num){
        this.num = num;
    }

    @Override
    public void run() {
        try {
            if(num == 1){
                lock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock2.lockInterruptibly();
            }else {
                lock2.lockInterruptibly();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock1.lockInterruptibly();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName() + "执行完毕");
            if(lock1.isHeldByCurrentThread()) { // 检查当前线程是否持有锁
                lock1.unlock();
            }
            if(lock2.isHeldByCurrentThread()) {
                lock2.unlock();
            }
            System.out.println(Thread.currentThread().getName() + "线程退出");
        }
    }
}